package com.ruoyi.common.sdk.baidu.api.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.ruoyi.common.sdk.baidu.Ocrbean;
import com.ruoyi.common.sdk.baidu.api.IOcrApi;
import com.ruoyi.common.sdk.baidu.request.OcrRequest;
import com.ruoyi.common.sdk.baidu.util.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OcrApiImpl implements IOcrApi {

    @Autowired
    Ocrbean ocrbean;

    private String getBaiduToken() {

        StringBuilder urlBuilder = new StringBuilder("https://aip.baidubce.com/");
        urlBuilder.append("oauth/2.0/token?grant_type=" + ocrbean.getGrantType() + "&client_id=" + ocrbean.getClientId() + "&client_secret=" + ocrbean.getClientSecret());

        String res = HttpUtils.sendGet(urlBuilder.toString());
        JSONObject jsonObject = JSONObject.parseObject(res);
        if(!jsonObject.containsKey("access_token")) throw new RuntimeException("获取百度认证失败！");

        return jsonObject.getString("access_token");
    }

    /**
     * 身份证识别
     */
    @Override
    public Object queryOcrImage(OcrRequest input) {

        StringBuilder path = new StringBuilder("https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=");
        path.append(getBaiduToken());
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path.toString());

        /**
         * 设置header参数
         */
        request.addHeaderParameter("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        /**
         * 设置jsonBody参数
         */
        String jsonBody = "id_card_side="+input.getIdCardSide()+"&url=" + input.getUrl();
        if("front".equals( input.getIdCardSide() )){
            jsonBody += "&detect_photo=true";
        }
        request.setJsonBody(jsonBody);
        ApiExplorerClient client = new ApiExplorerClient();
        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
            return JSONObject.parseObject(response.getResult());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
